package com.szewec.ps.ui.road.facilities.investigation.task;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSONObject;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.Enums;
import com.szewec.ps.databinding.ActivityRoadInvestigationTaskBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.ViewModeValue;
import com.szewec.ps.model.road.facilities.investigation.task.RoadFacilitiesInvestigationTask;
import com.szewec.ps.model.road.facilities.investigation.task.RoadFacilitiesInvestigationTaskDTO;
import com.szewec.ps.model.selectmappoint.SelectedPoint;
import com.szewec.ps.model.task.SurveyObjectModel;
import com.szewec.ps.myview.TitleViewWithAdd;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.ui.road.facilities.intersection.task.utils.BeanUtils;
import com.szewec.ps.ui.road.facilities.investigation.task.modern.urban.transit.RoadModernUrbanTransitActivity;
import com.szewec.ps.ui.road.facilities.investigation.task.roadside.facilities.RoadsideFacilitiesActivity;
import com.szewec.ps.util.CommonUtils;
import com.szewec.ps.util.GsonUtil;
import com.szewec.ps.util.RollUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.TextViewUtil;
import com.szewec.ps.util.okhttp.OkHttp;

import java.util.ArrayList;
import java.util.Arrays;

import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.ContentValues.TAG;

public class RoadInvestigationTaskActivity extends BaseActivity {
    private ActivityRoadInvestigationTaskBinding binding;

    /********字典start***********/
    // 道路等级
    private ArrayList<String> roadGradeDict = new ArrayList<>();
    // 断面形式
    private ArrayList<String> sectionFormDict = new ArrayList<>();
    // 单行路
    private ArrayList<String> oneWayRoadDict = new ArrayList<>();
    // 道路方向
    private ArrayList<String> roadDirectionDict = new ArrayList<>();
    /********字典end***********/

    // 路段设施调查任务DTO
    private RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO roadFacilitiesTaskDTO = new RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO();

    private String modeFlag; // 用于区分新增还是修改还是详情展示
    // 坐标
    private String selectedPoint;
    // 调查对象
    private SurveyObjectModel surveyObjectModel;
    private ViewModeValue viewModeValue;
    private RoadFacilitiesInvestigationTask investigationTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_road_investigation_task);
        ButterKnife.bind(this);

        // 初始化数据
        initData();
        initView();
        initTitleBar();

    }

    /**
     * 初始化数据
     */
    private void initData() {
        // 初始化字典
        roadGradeDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.roadGrade)));
        sectionFormDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.sectionForm)));
        oneWayRoadDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.oneWayRoad)));
        roadDirectionDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.roadDirection)));

        // 获取intent中的数据
        PresentValue<SurveyObjectModel> presentValue = (PresentValue<SurveyObjectModel>) getIntent().getSerializableExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK);
        //获取是新增还是修改还是详情展示
        assert presentValue != null;
        modeFlag = presentValue.getFlag();
        // 获取项目ID
        surveyObjectModel = presentValue.getT();
        Log.i("路段设施调查surveyObjectModel", JSONObject.toJSONString(surveyObjectModel));
        // 根据调查对象ID查询路段设施调查任务
        selectInvestigationTask();
    }

    /**
     * 查询路段设施调查任务
     */
    private void selectInvestigationTask() {
        OkHttp.get("/tpms-plan-service/api/road-facilities-investigation-task/" + surveyObjectModel.getId(), null, null, (result -> {
            Log.i("查询路段设施调查任务result", result);
            RoadFacilitiesInvestigationTaskDTO dto = GsonUtil.GsonToBean(result, RoadFacilitiesInvestigationTaskDTO.class);

            roadFacilitiesTaskDTO = dto.getData() == null ? new RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO() : dto.getData();
            // 设置页面内容
            setTextValue();
            setRightType();
        }));
    }

    /**
     * 初始化界面样式
     */
    private void initView() {
        viewModeValue = new ViewModeValue(this, modeFlag, binding.titleBar, binding.llContainer);
        // 点击按钮跳转到不同的页面
        onClickJumpPage();
    }

    /**
     * 设置Title
     */
    private void initTitleBar() {
        //设置导航栏右侧按钮
        if (Constants.PRESENT_VALUE_FLAG.VIEW.equals(modeFlag)) {
            CommonUtils.setViewMode(viewModeValue, this::finish, this::callMoreMenu);
        } else if (Constants.PRESENT_VALUE_FLAG.ADD.equals(modeFlag)
                || Constants.PRESENT_VALUE_FLAG.EDIT.equals(modeFlag)) {
            CommonUtils.setViewMode(viewModeValue, this::finish, this::appendOrModifyData);
        }
    }

    /**
     * 保存
     */
    private void appendOrModifyData() {
        if (!checkData()) {
            Log.e(TAG, "新增/修改路段设施调查 数据校验失败");
            return;
        }
        setRoadFacilitiesTask();

        Log.i("路段设施调查 paramData", JSONObject.toJSONString(roadFacilitiesTaskDTO));
        String url = "";
        // ID不为空 视为编辑
        if (StringUtils.isNotEmpty(roadFacilitiesTaskDTO.getFacilitiesInvestigationTask().getId())) {
            url = "/tpms-plan-service/api/road-facilities-investigation-task/update";
        } else {
            url = "/tpms-plan-service/api/road-facilities-investigation-task/save";
        }
        OkHttp.post(url, roadFacilitiesTaskDTO, (result -> {
            JSONObject jsonObject = JSONObject.parseObject(result);
            Log.i(TAG, "create task result is：" + jsonObject);

            String code = (String) jsonObject.get("code");
            assert code != null;

            if (!Enums.ResponseCodeEnum.请求成功.getKey().equals(Integer.valueOf(code))) {
                Object msg = jsonObject.get("msg");
                BamToast.showText(this, "请求错误：" + msg);
                return;
            }

            BamToast.showText(this, "保存成功");
            setResult(RESULT_OK, new Intent());
            finish();
        }));
    }

    /**
     * 设置路段调查对象
     */
    private void setRoadFacilitiesTask() {
        investigationTask.setSurveyObjectId(surveyObjectModel.getId());
        investigationTask.setRoadName(binding.roadName.getStringValue());
        investigationTask.setRoadGrade(Enums.RoadGradeEnum.getKeyByValue(binding.roadGrade.getStringValue()));
        investigationTask.setCoordinate(selectedPoint);
        investigationTask.setSectionForm(Enums.RoadSectionFormEnum.getKeyByValue(binding.sectionForm.getStringValue()));
        investigationTask.setOneWayRoad(Enums.OneWayRoadEnum.getKeyByValue(binding.oneWayRoad.getStringValue()));
        investigationTask.setRoadDirection(Enums.RoadDirectionEnum.getKeyByValue(binding.roadDirection.getStringValue()));
        roadFacilitiesTaskDTO.setFacilitiesInvestigationTask(investigationTask);
    }

    /**
     * 校验必填项
     */
    private boolean checkData() {
        if (StringUtils.isEmpty(binding.roadGrade.getStringValue()) || StringUtils.isEmpty(binding.sectionForm.getStringValue())) {
            BamToast.showText(this, R.string.requires_text_filed_check, false);
            return false;
        }
        return true;
    }

    private void callMoreMenu() {
        CommonUtils.showMoreMenu(this, binding.titleBar.getRightLayout(), this::linkToEditActivity, this::deleteData);
    }

    private void deleteData() {

    }

    private void linkToEditActivity() {
    }

    /**
     * 设置页面内容
     */
    private void setTextValue() {
        investigationTask = roadFacilitiesTaskDTO.getFacilitiesInvestigationTask() == null
                ? new RoadFacilitiesInvestigationTask() : roadFacilitiesTaskDTO.getFacilitiesInvestigationTask();

        // 道路名称 设置默认值
        String roadName = StringUtils.isEmpty(investigationTask.getRoadName()) ? surveyObjectModel.getSurveyName() : investigationTask.getRoadName();
        // 单行路 设置默认值
        Integer oneWayRoad = investigationTask.getOneWayRoad();
        oneWayRoad = oneWayRoad == null ? 0 : oneWayRoad;
        // 获取坐标
        SelectedPoint selectedPoint = JSONObject.parseObject(investigationTask.getCoordinate(), SelectedPoint.class);
        selectedPoint = selectedPoint == null ? new SelectedPoint() : selectedPoint;

        binding.roadName.setValue(roadName);
        // 道路名称不可编辑
        binding.roadName.switchoverMode(false);
        binding.coordinate.setValue(selectedPoint.getxCoordinate(), selectedPoint.getyCoordinate());
        binding.roadGrade.setValue(Enums.RoadGradeEnum.getValueByKey(investigationTask.getRoadGrade()));
        binding.sectionForm.setValue(Enums.RoadSectionFormEnum.getValueByKey(investigationTask.getSectionForm()));
        binding.oneWayRoad.setValue(Enums.OneWayRoadEnum.getValueByKey(oneWayRoad));
        binding.roadDirection.setValue(Enums.RoadDirectionEnum.getValueByKey(investigationTask.getRoadDirection()));
    }

    /**
     * 如果是修改 将右边的“添加”按钮修改为 > 符号
     */
    private void setRightType() {
        if (BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadMotorway())) {
            binding.roadMotorway.setRightType(TitleViewWithAdd.EDIT);
        }
        if (BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadTrafficIsolationFacilities())) {
            binding.traffic.setRightType(TitleViewWithAdd.EDIT);
        }
        if (BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadSlowLane())) {
            binding.slowLane.setRightType(TitleViewWithAdd.EDIT);
        }
        if (BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadBridge())) {
            binding.bridge.setRightType(TitleViewWithAdd.EDIT);
        }
        if (BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadTunnel())) {
            binding.tunnel.setRightType(TitleViewWithAdd.EDIT);
        }
        // 现代轨道交通 需要判断三个
        if (BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadModernUrbanTransitBRT())
                || BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadModernUrbanTransitLightRail())
                || BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadModernUrbanTransitTram())) {
            binding.railTransit.setRightType(TitleViewWithAdd.EDIT);
        }
        // 道路沿线设施 需要判断八个
        if (BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadFacilitiesBusStop())
                || BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadMetroStation())
                || BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadMetroStationGetway())
                || BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadParking())
                || BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadBicycleParking())
                || BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadCrossingFacilities())
                || BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadTollGate())
                || BeanUtils.checkObjFieldIsNotNull(roadFacilitiesTaskDTO.getRoadTrafficSign())) {
            binding.roadSideFacilities.setRightType(TitleViewWithAdd.EDIT);
        }
    }

    /**
     * 点击按钮跳转到不同的页面
     */
    private void onClickJumpPage() {
        // 机动车道
        binding.roadMotorway.setIronClickListener(v -> {
            Intent intent = new Intent(this, RoadMotorwayActivity.class);
            PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.ADD, roadFacilitiesTaskDTO);
            intent.putExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO, presentValue);
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this::childSaveClickListener).launch(intent);
        });
        // 交通隔离设施
        binding.traffic.setIronClickListener(v -> {
            // 判断是否录入了机动车道信息
            if (roadFacilitiesTaskDTO.getRoadMotorway() == null || roadFacilitiesTaskDTO.getRoadMotorway().getLaneTotal() == null) {
                BamToast.showText(this, "请先添加 机动车道 数据！", false);
                return;
            }
            Intent intent = new Intent(this, RoadIsolationFacilitiesActivity.class);
            PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.ADD, roadFacilitiesTaskDTO);
            intent.putExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO, presentValue);
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this::childSaveClickListener).launch(intent);
        });
        // 慢行道
        binding.slowLane.setIronClickListener(v -> {
            Intent intent = new Intent(this, RoadSlowLaneActivity.class);
            PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.ADD, roadFacilitiesTaskDTO);
            intent.putExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO, presentValue);
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this::childSaveClickListener).launch(intent);
        });
        // 桥梁
        binding.bridge.setIronClickListener(v -> {
            Intent intent = new Intent(this, RoadBridgeActivity.class);
            PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.ADD, roadFacilitiesTaskDTO);
            intent.putExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO, presentValue);
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this::childSaveClickListener).launch(intent);
        });
        // 隧道
        binding.tunnel.setIronClickListener(v -> {
            Intent intent = new Intent(this, RoadTunnelActivity.class);
            PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.ADD, roadFacilitiesTaskDTO);
            intent.putExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO, presentValue);
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this::childSaveClickListener).launch(intent);
        });
        // 现代轨道交通
        binding.railTransit.setIronClickListener(v -> {
            Intent intent = new Intent(this, RoadModernUrbanTransitActivity.class);
            PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.ADD, roadFacilitiesTaskDTO);
            intent.putExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO, presentValue);
//            startActivity(intent);
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this::childSaveClickListener).launch(intent);
        });
        // 道路沿线设施
        binding.roadSideFacilities.setIronClickListener(v -> {
            Intent intent = new Intent(this, RoadsideFacilitiesActivity.class);
            PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.ADD, roadFacilitiesTaskDTO);
            intent.putExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO, presentValue);
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this::childSaveClickListener).launch(intent);
        });
    }

    /**
     * 子页面保存之后的回调函数
     */
    private void childSaveClickListener(ActivityResult result) {
        if (result.getData() != null) {
            PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue =
                    (PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO>) result.getData().getSerializableExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO);
            assert presentValue != null;
            roadFacilitiesTaskDTO = presentValue.getT();
        }
        // 重新设置右边的图标
        setRightType();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SelectedPoint centerPoint = null;
        //选择了坐标
        if (resultCode == Constants.RESULT_CODE.SELECTED_POINT) {
            if (data != null) {
                Bundle presentValue = data.getExtras();
                centerPoint = (SelectedPoint) presentValue.getSerializable(Constants.EXTRA_KEY.MAP_CENTER_POINT);
            }
        }
        if (centerPoint == null) {
            return;
        }
        selectedPoint = JSONObject.toJSONString(centerPoint);
    }

    @OnClick({R.id.roadGrade, R.id.sectionForm, R.id.oneWayRoad, R.id.roadDirection})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.roadGrade:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, roadGradeDict, binding.roadGrade.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.roadGrade.setValue(roadGradeDict.get(index));
                    }
                });
                break;
            case R.id.sectionForm:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, sectionFormDict, binding.sectionForm.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.sectionForm.setValue(sectionFormDict.get(index));
                    }
                });
                break;
            case R.id.oneWayRoad:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, oneWayRoadDict, binding.oneWayRoad.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.oneWayRoad.setValue(oneWayRoadDict.get(index));
                    }
                });
                break;
            case R.id.roadDirection:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, roadDirectionDict, binding.roadDirection.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.roadDirection.setValue(roadDirectionDict.get(index));
                    }
                });
                break;
        }
    }
}
